#include "resource_scanner.h"
//#include "bnb_controller.h"
#include "lua_controller.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

#include <sstream>
using namespace std;

void ResourceScanner::
scan (map<string,string>& resources, const string& rootpath) {
  stringstream ss;

  try {
    LuaController ctrl;
    ctrl.loadScript(resource_scanner_script);

    ss << "Scanning for resources in : " << rootpath;
    LOG(ss.str());

    lua_State* L = ctrl.getState();
    lua_getglobal(L, "scan_resources");
    lua_pushstring(L, rootpath.c_str());
    lua_call(L, 1, 1); 

    ctrl.getStringTable(resources);
  }
  catch (TypeCastException& e) {
    // Note that the TypeCastException is automatically logged as an error.
    LOG_ERROR("Resource scanning was interrupted by an error.");
    return;
  }
  catch (string& e) {
    LOG_FATAL(e);
  }
}

#ifdef TEST_RESOURCE_SCANNER
#include "bnb_controller.h"
#define rootpath "/Volumes/MacAPPS/Development/brick-and-blast/data"
int main (int argc, char** argv) {
  BNBController* bnbCtrl = BNBController::getInstance();
  bnbCtrl->initialize();

  map<string,string> resources;
  ResourceScanner::scan(resources, rootpath);
  
  map<string,string>::const_iterator itr;
  
  cout << "Found " << resources.size() << " resources." << endl;
  for (itr = resources.begin(); itr != resources.end(); ++itr) {
    cout << (*itr).first << " " << (*itr).second << endl;
  }

  bnbCtrl->terminate();
  return EXIT_SUCCESS;
}
#endif

